'use client';

import React, { useState } from 'react';
import Button from '@/components/ui/Button';
import { 
  Plus,
  Search,
  Play,
  Pause,
  RotateCcw,
  Eye,
  Clock,
  Database,
  BrainCircuit,
  Activity,
  CheckCircle,
  XCircle,
  Users,
  BarChart3
} from 'lucide-react';

interface Task {
  id: string;
  name: string;
  type: 'incremental_learning' | 'collaborative_evolution' | 'quantization';
  status: 'pending' | 'running' | 'completed' | 'failed' | 'paused';
  progress: number;
  dataset: string;
  model: string;
  startTime: string;
  endTime?: string;
  cloudNodes: number;
  edgeNodes: number;
  accuracy?: number;
}

export default function TasksPage() {
  const [tasks] = useState<Task[]>([
    {
      id: '1',
      name: '人员作业识别模型训练',
      type: 'incremental_learning',
      status: 'running',
      progress: 75,
      dataset: '作业场景数据集v3.2',
      model: 'PowerVision-Workers',
      startTime: '2024-12-03 09:30:00',
      cloudNodes: 2,
      edgeNodes: 4,
      accuracy: 87.5
    },
    {
      id: '2',
      name: '设备缺陷识别增量学习',
      type: 'incremental_learning',
      status: 'completed',
      progress: 100,
      dataset: '设备缺陷图像数据集',
      model: 'PowerNet-Defect',
      startTime: '2024-12-03 08:00:00',
      endTime: '2024-12-03 12:00:00',
      cloudNodes: 1,
      edgeNodes: 2,
      accuracy: 94.2
    },
    {
      id: '3',
      name: '环境隐患识别协同优化',
      type: 'collaborative_evolution',
      status: 'pending',
      progress: 0,
      dataset: '环境隐患检测数据集',
      model: 'PowerGuard-Environment',
      startTime: '2024-12-03 15:00:00',
      cloudNodes: 1,
      edgeNodes: 3,
    },
    {
      id: '4',
      name: '大模型INT8量化任务',
      type: 'quantization',
      status: 'running',
      progress: 45,
      dataset: '量化测试数据集',
      model: 'PowerLLM-Large',
      startTime: '2024-12-03 10:15:00',
      cloudNodes: 1,
      edgeNodes: 0,
    },
    {
      id: '5',
      name: '序列数据缺陷识别训练',
      type: 'incremental_learning',
      status: 'failed',
      progress: 25,
      dataset: '时序缺陷数据集',
      model: 'PowerSeq-Defect',
      startTime: '2024-12-03 07:45:00',
      endTime: '2024-12-03 08:30:00',
      cloudNodes: 1,
      edgeNodes: 1,
    }
  ]);

  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [typeFilter, setTypeFilter] = useState('all');

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'running':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 border border-blue-200">
          <span className="w-1.5 h-1.5 bg-blue-600 rounded-full mr-1.5"></span>
          运行中
        </span>;
      case 'completed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 border border-green-200">
          <span className="w-1.5 h-1.5 bg-green-600 rounded-full mr-1.5"></span>
          已完成
        </span>;
      case 'pending':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 border border-yellow-200">
          <span className="w-1.5 h-1.5 bg-yellow-600 rounded-full mr-1.5"></span>
          待执行
        </span>;
      case 'failed':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-200">
          <span className="w-1.5 h-1.5 bg-red-600 rounded-full mr-1.5"></span>
          失败
        </span>;
      case 'paused':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          <span className="w-1.5 h-1.5 bg-gray-600 rounded-full mr-1.5"></span>
          已暂停
        </span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 border border-gray-200">
          {status}
        </span>;
    }
  };

  const getTypeBadge = (type: string) => {
    switch (type) {
      case 'incremental_learning':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-blue-100 text-blue-800">增量学习</span>;
      case 'collaborative_evolution':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-green-100 text-green-800">协同进化</span>;
      case 'quantization':
        return <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-purple-100 text-purple-800">模型量化</span>;
      default:
        return <span className="inline-flex items-center px-2 py-0.5 rounded-md text-xs font-medium bg-gray-100 text-gray-800">{type}</span>;
    }
  };

  const filteredTasks = tasks.filter(task => {
    return (
      (searchTerm === '' || task.name.toLowerCase().includes(searchTerm.toLowerCase())) &&
      (statusFilter === 'all' || task.status === statusFilter) &&
      (typeFilter === 'all' || task.type === typeFilter)
    );
  });

  const getActionButtons = (task: Task) => {
    if (task.status === 'pending') {
      return (
        <div className="flex items-center gap-1">
          <Button size="sm" variant="primary">
            <Play className="h-3 w-3" />
          </Button>
          <Button size="sm" variant="secondary">
            <Eye className="h-3 w-3" />
          </Button>
        </div>
      );
    }
    
    if (task.status === 'running') {
      return (
        <div className="flex items-center gap-1">
          <Button size="sm" variant="secondary">
            <Pause className="h-3 w-3" />
          </Button>
          <Button size="sm" variant="secondary">
            <Eye className="h-3 w-3" />
          </Button>
        </div>
      );
    }
    
    if (task.status === 'paused') {
      return (
        <div className="flex items-center gap-1">
          <Button size="sm" variant="primary">
            <Play className="h-3 w-3" />
          </Button>
          <Button size="sm" variant="secondary">
            <Eye className="h-3 w-3" />
          </Button>
        </div>
      );
    }
    
    if (['failed', 'completed'].includes(task.status)) {
      return (
        <div className="flex items-center gap-1">
          <Button size="sm" variant="secondary">
            <RotateCcw className="h-3 w-3" />
          </Button>
          <Button size="sm" variant="secondary">
            <Eye className="h-3 w-3" />
          </Button>
        </div>
      );
    }
    
    return (
      <Button size="sm" variant="secondary">
        <Eye className="h-3 w-3" />
      </Button>
    );
  };

  return (
    <div className="space-y-4">
      {/* 紧凑的标题栏 */}
      <div className="flex items-center justify-between rounded-lg px-4 py-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900">进化任务管理</h1>
          <p className="text-sm text-gray-600 mt-0.5">任务执行与监控</p>
        </div>
        <Button variant="primary" size="sm">
          <Plus className="h-4 w-4 mr-1.5" />
          新建任务
        </Button>
      </div>

      {/* 紧凑的指标卡片 */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">运行中</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {tasks.filter(t => t.status === 'running').length}
              </div>
            </div>
            <Activity className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">已完成</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {tasks.filter(t => t.status === 'completed').length}
              </div>
            </div>
            <CheckCircle className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">待执行</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {tasks.filter(t => t.status === 'pending').length}
              </div>
            </div>
            <Clock className="h-6 w-6 text-green-600" />
          </div>
        </div>
        
        <div className="bg-gray-50 border border-gray-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div>
              <div className="text-xs font-medium text-green-700 uppercase tracking-wide">失败</div>
              <div className="text-2xl text-green-700 font-bold mt-1">
                {tasks.filter(t => t.status === 'failed').length}
              </div>
            </div>
            <XCircle className="h-6 w-6 text-green-600" />
          </div>
        </div>
      </div>

      {/* 紧凑的搜索栏 */}
      <div className="bg-white border border-gray-200 rounded-lg px-4 py-3 shadow-sm">
        <div className="flex flex-col sm:flex-row gap-3">
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
              <input
                type="text"
                placeholder="搜索任务名称..."
                className="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
          <div className="flex gap-3">
            <select
              className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
            >
              <option value="all">全部状态</option>
              <option value="running">运行中</option>
              <option value="completed">已完成</option>
              <option value="pending">待执行</option>
              <option value="failed">失败</option>
              <option value="paused">已暂停</option>
            </select>
            <select
              className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
            >
              <option value="all">全部类型</option>
              <option value="incremental_learning">增量学习</option>
              <option value="collaborative_evolution">协同进化</option>
              <option value="quantization">模型量化</option>
            </select>
          </div>
        </div>
      </div>

      {/* 专业的任务表格 */}
      <div className="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务信息</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">进度</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数据集</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">模型</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">资源</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">准确率</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredTasks.map((task) => (
                <tr key={task.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-4 py-3">
                    <div className="min-w-0">
                      <div className="text-sm font-medium text-gray-900 truncate">{task.name}</div>
                      <div className="text-xs text-gray-500 mt-1">开始时间: {task.startTime}</div>
                      {task.endTime && (
                        <div className="text-xs text-gray-500">结束时间: {task.endTime}</div>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    {getTypeBadge(task.type)}
                  </td>
                  <td className="px-4 py-3 text-center">
                    {getStatusBadge(task.status)}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className="w-full">
                      <div className="flex items-center justify-center mb-1">
                        <span className="text-sm font-medium text-gray-900">{task.progress}%</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-1.5">
                        <div 
                          className={`h-1.5 rounded-full transition-all duration-300 ${
                            task.status === 'completed' ? 'bg-green-600' : 
                            task.status === 'failed' ? 'bg-red-600' : 
                            'bg-blue-600'
                          }`}
                          style={{ width: `${task.progress}%` }}
                        ></div>
                      </div>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center text-sm text-gray-900">
                      <Database className="h-4 w-4 text-gray-400 mr-2 flex-shrink-0" />
                      <span className="truncate">{task.dataset}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center text-sm text-gray-900">
                      <BrainCircuit className="h-4 w-4 text-gray-400 mr-2 flex-shrink-0" />
                      <span className="truncate">{task.model}</span>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <div className="text-xs text-gray-700">
                      <div>云端: {task.cloudNodes}</div>
                      <div>边缘: {task.edgeNodes}</div>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    {task.accuracy ? (
                      <div className="text-sm font-semibold text-green-600">{task.accuracy}%</div>
                    ) : (
                      <span className="text-xs text-gray-400">-</span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-center">
                    {getActionButtons(task)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        
        {/* 页面底部统计汇总 */}
        <div className="border-t border-gray-200 bg-gray-50 px-4 py-3">
          <div className="flex items-center justify-between text-sm text-gray-600">
            <div className="flex items-center gap-6">
              <span>共 {tasks.length} 个任务</span>
              <span>运行中: {tasks.filter(t => t.status === 'running').length}</span>
              <span>已完成: {tasks.filter(t => t.status === 'completed').length}</span>
            </div>
            <div className="flex items-center gap-6">
              <span>平均进度: {Math.round(tasks.reduce((sum, t) => sum + t.progress, 0) / tasks.length)}%</span>
              <span>总资源: {tasks.reduce((sum, t) => sum + t.cloudNodes + t.edgeNodes, 0)}节点</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
} 